<template>
  <div class="complain-center">
    <div class="personal-info">
      <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
        <!-- 新增投诉建议按钮 -->
        <h2 class="title-style">投诉与建议中心</h2>
        <el-button type="primary" @click="showAddComplaintDialog = true" style="text-align: right;">新增投诉建议</el-button>

        <!-- 新增投诉建议对话框 -->
        <el-dialog v-model="showAddComplaintDialog" title="新增投诉建议">
          <template #default>
            <el-form ref="formRef" :model="newComplaint" label-width="80px">
              <el-form-item label="类型">
                <el-select v-model="newComplaint.type" placeholder="请选择类型">
                  <el-option label="投诉" value="投诉"></el-option>
                  <el-option label="建议" value="建议"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="内容">
                <el-input
                    v-model="newComplaint.complaintContent"
                    type="textarea"
                    placeholder="请输入投诉内容"
                />
              </el-form-item>

              <el-form-item label="附件">
                <input type="file" ref="fileInput" @change="handleFileChange" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
              </el-form-item>
            </el-form>
          </template>
          <template #footer>
            <el-button @click="showAddComplaintDialog = false">取消</el-button>
          </template>
        </el-dialog>

        <!-- 加载中提示 -->
        <div v-if="isLoading" class="loading-container">加载中...</div>

        <!-- 投诉建议列表 -->
        <template v-else-if="complaints && complaints.length > 0">
          <table style="text-align: center; width: 99%; border-collapse: collapse; ">
            <thead>
            <tr>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">类型</th>
              <th style="width: 180px; height: 50px; border: 1px solid #eee;">内容</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">附件</th>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">投诉(建议)时间</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">状态</th>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">物业整改措施</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">完成时间</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(row, index) in complaints" :key="index" style="border: 1px solid #eee;">
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.type" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 180px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.complainContent" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-button v-if="row.attachment" type="text" @click="downloadFile(row.attachment)">下载附件</el-button>
                <span v-else>无</span>
              </td>
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                {{ formatDate(row.complainDate) }}
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.processingStatus" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                <el-input v-if="row.measure" v-model="row.measure" disabled class="disabled-style"></el-input>
                <span v-else>无</span>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                {{ formatDate(row.completionDate) }}
              </td>
            </tr>
            </tbody>
          </table>
        </template>
        <template v-else>
          <p>暂无投诉建议记录</p>
        </template>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { ref } from 'vue'
const count = ref(0)
const load = () => {
  count.value += 2
}
export default {
  name: "ComplaintCenter",
  data() {
    return {
      showAddComplaintDialog: false,
      newComplaint: {
        type: '',
        communityId: null,
        ownerId: null,
        complaintContent: '',
        attachment: null,
        complaintDate: '',
        processingStatus: '待处理',
        measure: '',
        handlerId: null,
        completionDate: null
      },
      formRef: null,
      complaints: [],
      isLoading: false,
      formatDate: function (date) {
        if (!date) return '';
        return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
      }
    };
  },
  mounted() {
    this.getComplaints();
  },
  methods: {
    async getComplaints() {
      this.isLoading = true;
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/complain/personal', {
          headers: {
            Authorization: token
          }
        });
        this.complaints = response.data.data;
        // 前端排序，确保按待处理、处理中、已处理的顺序展示，时间近的靠前
        this.complaints.sort((a, b) => {
          const statusOrder = { '待处理': 1, '处理中': 2, '已完成': 3 };
          const statusA = statusOrder[a.processingStatus];
          const statusB = statusOrder[b.processingStatus];
          if (statusA!== statusB) {
            return statusA - statusB;
          }
          const dateA = dayjs(a.complainDate);
          const dateB = dayjs(b.complainDate);
          const now = dayjs();
          // 计算与当前时间差值的绝对值，差值越小越靠前
          const diffA = Math.abs(now.diff(dateA, 'millisecond'));
          const diffB = Math.abs(now.diff(dateB, 'millisecond'));
          return diffA - diffB;
        });
      } catch (error) {
        ElMessage.error('获取投诉建议列表时出错：' + error.message);
      } finally {
        this.isLoading = false;
      }
    },
    handleFileChange(event) {
      this.newComplaint.attachment = event.target.files[0];
    },
    async submitForm() {
      this.isLoading = true;
      const formData = new FormData();
      formData.append('complaintContent', this.newComplaint.complaintContent);
      formData.append('attachment', this.newComplaint.attachment);
      formData.append('type', this.newComplaint.type);

      try {
        const token = localStorage.getItem('token');
        const communityId = localStorage.getItem('communityId');
        const response = await axios.post(`/api/complain/${communityId}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: token
          }
        });
        if (response.data.code === 200) {
          ElMessage.success('提交成功');
        } else {
          ElMessage.error('提交失败，请输入正确信息');
        }
        this.showAddComplaintDialog = false;
        this.getComplaints();
      } catch (error) {
        ElMessage.error('提交失败：' + error.response?.data?.msg || error.message);
      } finally {
        this.isLoading = false;
      }
    },
    async downloadFile(path) {
      this.isLoading = true;
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/file', {
          params: {
            path: path
          },
          headers: {
            Authorization: token
          },
          responseType: 'blob'
        });
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition ? contentDisposition.split('filename*=UTF-8\'\'')[1] : 'downloaded_file';
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        ElMessage.success('文件下载成功');
      } catch (error) {
        ElMessage.error('文件下载失败：' + error.message);
      } finally {
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>

.el-button {
  margin-bottom: 20px;

}

.complain-center {
  padding: 15px;
  display: flex;
  width: 100%;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中，可按需选择是否添加 */
}

.personal-info {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  width: 80%;
  height: 80%;
  background-color: #ffffff; /* 将背景颜色设置为白色 */
}

.title-style {
  margin-bottom: 20px;
  color: #136bbd;
}

.infinite-list {
  height: 440px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

table {
  width: 80%; /* 调整表格宽度，使其更合适 */
  margin: 0 auto; /* 让表格在父元素中水平居中 */
  border-collapse: collapse;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

table td {
  padding: 12px;
  vertical-align: middle; /* 新增垂直居中属性 */
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 16px;
  color: #666;
}

</style>